//
//  QAExpertsViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/9/27.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "QAExpertsViewController.h"
#import "QAExpertsTableViewCell.h"
#import "User.h"
#import "HomeServer.h"
#import "TCMsgHandler.h"

@interface QAExpertsViewController ()<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, assign) NSInteger page; // 网络请求页数
@property (nonatomic, strong) NSMutableArray *infoArr;

@end

@implementation QAExpertsViewController {
    UITableView *_tableView;
    QAExpertsTableViewCell *_cell;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.page = 1;
    
    [self buildUI];
    
    [self refreshData];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [self GETExpertsList];
}

#pragma mark ==========构建UI==========
- (void)buildUI {
    
    self.view.backgroundColor = UISeparatedColorRGB;
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 1, SCREEN_WIDTH, SCREEN_HEIGHT-64-44-1) style:UITableViewStylePlain];
    [self.view addSubview:_tableView];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.tableFooterView = [[UIView alloc]init];
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [_tableView registerNib:[UINib nibWithNibName:@"QAExpertsTableViewCell" bundle:nil] forCellReuseIdentifier:@"qaZone"];
    
}

#pragma mark ==========更新数据==========
- (void)refreshData {
    __weak typeof (self) weakSelf = self;
    
    _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"下拉刷新");
        weakSelf.page = 1;
        [weakSelf GETExpertsList];
    }];
    
    _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        NSLog(@"上拉加载");
        weakSelf.page++;
        [weakSelf GETExpertsList];
    }];
    
}


#pragma mark ==========UITableView==========
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    _cell = [tableView dequeueReusableCellWithIdentifier:@"qaZone"];
    
    _cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    User *model = self.infoArr[indexPath.row];
    
    _cell.model = model;
    
    _cell.focus.tag = indexPath.row+1;
    [_cell.focus addTarget:self action:@selector(focusClick:) forControlEvents:UIControlEventTouchUpInside];
    
    _cell.chat.tag = indexPath.row+1;
    [_cell.chat addTarget:self action:@selector(chatClick:) forControlEvents:UIControlEventTouchUpInside];
    
    return _cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.infoArr.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    CGFloat cellH = [_cell cellHeight];
    if (cellH == 0) {
        return 10;
    }
    else
        return [_cell cellHeight];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    NSLog(@"点击tableView.cell = %ld", indexPath.row);
}


#pragma mark ===========响应方法==========
/**
 获取资讯列表
 */
- (void)GETExpertsList {
    
    if (GetUserDefaule(USERINFO) == NULL) {
        [_tableView.mj_header endRefreshing];
        [_tableView.mj_footer endRefreshing];
//        [self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
        return;
    }
    
    // GET /articles 获取（查询）资讯列表 keyword 关键词，匹配商品名 page 页码，默认为1 per_page 每页显示数，默认为10 cate_id 二级分类ID，暂不支持一级分类搜索 orderby 排序字段
    
    NSDictionary *param = @{@"page":[NSString stringWithFormat:@"%ld", self.page],
                            @"per_page":@"10"};
    
    [[NetworkTool sharedTool] requestWithName:@"获取在线专家" URLString:APISpecialists parameters:param method:@"GET" callBack:^(id responseObject) {
        
        
        NSArray *arr = responseObject[@"data"];
        
        if (self.page == 1) {
            [self.infoArr removeAllObjects];
        }
        
        if (arr.count == 0) {
            self.page--;
            if (self.page == 0) {
                self.page = 1;
            }
        }
        for (NSDictionary *dic in arr) {
            User *model = [[User alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.infoArr addObject:model];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [_tableView.mj_header endRefreshing];
            [_tableView.mj_footer endRefreshing];
            [_tableView reloadData];
        });
    }];
    
}


// 关注
- (void)focusClick:(UIButton *)sender {
    
    User *model = self.infoArr[sender.tag-1];
    NSString *toId = [NSString stringWithFormat:@"%ld", model.user_id];
    
    [HomeServer focus:sender toId:toId];
}

- (void)chatClick:(UIButton *)sender{
    
    User *model = self.infoArr[sender.tag-1];
//    NSString *toId = [NSString stringWithFormat:@"%ld", model.user_id];
//    TIMConversation *cc = [[TIMManager sharedInstance] getConversation:TIM_C2C receiver:toId];
    
    IMAUser *user = [[IMAUser alloc] init];
    user.nickName = model.nickname;
    user.userId = [NSString stringWithFormat:@"%ld",model.user_id];
    user.remark = model.nickname;
    user.icon = model.face;
    
    #if kTestChatAttachment
        // 无则重新创建
        ChatViewController *chatVC = [[CustomChatUIViewController alloc] initWith:user];
    #else
    ChatViewController *chatVC = [[IMAChatViewController alloc] initWith:user];
    #endif
    
    
    // 隐藏底部的buttomBar 当 push 的时候
    //        [self setHidesBottomBarWhenPushed:YES];
    [self.navigationController pushViewController:chatVC animated:YES];
    
}

// 懒加载
- (NSMutableArray *)infoArr {
    if (_infoArr == nil) {
        _infoArr = [[NSMutableArray alloc] init];
    }
    return _infoArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
